package com.mybatis.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;


/**
 * mybatis工具类
 */
public class MybatisUtil {

    private static SqlSessionFactory ssf; // 会话工厂

    // 只执行一次
    static {
        try {
            // 读取配置文件mybatis-config.xml
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            // 获取会话工厂
            ssf = new SqlSessionFactoryBuilder().build(is, "smbms");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得会话
     */
    public static SqlSession getSqlSession() {
        // 是否自动提交事务  true:自动提交   false:手动提交
        return ssf.openSession(true);
    }

    /**
     * 释放会话
     */
    public static void closeSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();  //关闭 session
        }
    }

    public static void main(String[] args) {
        getSqlSession();
    }


}
